<template>
  <div class="release_box">
    <div class="head">
      <p class="close" @click="close">
        <u-icon name="close" color="#999999" size="18"></u-icon>
      </p>
    </div>
    <div class="list flex_l">
      <p class="title">付款金额</p>
      <input v-model="form.price" type="number" placeholder="请输入" />
    </div>
    <div class="list flex_l">
      <p class="title">收款人ID号</p>
      <input
        v-model="form.payeeId"
        type="text"
        placeholder="请输入"
        @input="changePayeeId"
      />
    </div>
    <div class="list flex_l" v-if="receiveInfo">
      <p class="title">收款用户信息</p>
      <div class="user-info">
        <img :src="receiveInfo.avatar" alt="" />
        <div>{{ receiveInfo.nickname }}</div>
      </div>
    </div>
    <div class="list" style="border-bottom: none">
      <p class="title" style="margin-bottom: 30rpx">付款备注<span>*</span></p>
      <u--textarea
        v-model="form.remark"
        placeholder="简述交易事项（限制20字）"
      ></u--textarea>
    </div>

    <div class="play_box">
      <p class="title">支付方式</p>
      <div class="radio-group-container">
        <radio-group v-model="selected" @change="changePlayType">
          <label
            class="radio-label"
            v-for="option in options"
            :key="option.value"
            @click="changePayType(option)"
          >
            <div class="text">
              <img :src="option.icon" alt="" />
              {{ option.text }}
              <span v-if="option.value === '2'">(账户余额{{ balance }}元)</span>
            </div>
            <!-- <radio v-model="option.value" /> -->
            <img
              class="gx"
              src="/static/xz.png"
              v-if="option.value === selected"
            />
          </label>
        </radio-group>
      </div>
    </div>

    <div class="xieyi">
      <u-checkbox-group
        size="14"
        v-model="checkboxValue"
        placement="column"
        activeColor="#23AC39"
      >
        <u-checkbox> </u-checkbox>
      </u-checkbox-group>
      <p @click="clickGou">
        本人已阅读并同意<span @click="toXieyi">《资金担保协议》</span>
      </p>
    </div>

    <div class="btn">
      <u-button
        @click="submit"
        :disabled="isDisable"
        loadingMode="circle"
        :loading="isDisable"
        loadingText="支付中..."
        type="primary"
        text="确定"
      >
      </u-button>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex"
import api from "@/api"
import Config from "@/config/index.js"
import { Debounce } from "@/utils/utils.js"
export default {
  options: {
    styleIsolation: "shared",
  },
  props: {
    walletInfo: {
      type: Object,
      default: () => {},
    },
  },

  data() {
    return {
      receiveInfo: null,
      form: {
        payerId: "",
        payerName: "",
        price: "",
        payeeId: "",
        payeeName: "",
        remark: "",
      },
      checkboxValue: [],
      isDisable: false, // 提交
      selected: "1",
      selectedItem: null,
      options: [
        {
          icon: "/static/wx_play.png",
          value: "1",
          text: "微信支付",
        },
        {
          icon: "https://zxsd-oss-img.oss-cn-chengdu.aliyuncs.com/10c50be1c6aa34cd49daf87877fce0a73eab58fe5a38bf92fc35be19e12ab0b3.jpg",
          value: "2",
          text: "余额支付",
        },
      ],
    }
  },
  computed: {
    ...mapState({
      userName: (state) => state.user.userName,
      userId: (state) => state.user.userId,
      token: (state) => state.user.token,
      userTx: (state) => state.user.userTx,
    }),
    balance() {
      return (
        this.walletInfo?.balance && (this.walletInfo.balance / 100).toFixed(2)
      )
    },
  },
  watch: {},
  methods: {
    //修改收款人
    changePayeeId: Debounce(async function (e) {
      if (!e.detail.value) {
        this.receiveInfo = null
        return
      }
      try {
        const res = await api.user.get_by_id({ id: e.detail.value })
        this.receiveInfo = res.data
      } catch (e) {}
    }, 500),
    toXieyi() {
      uni.navigateTo({
        url: `/pages/authorization/dbxieyi/index`,
      })
    },

    clickGou() {
      if (this.checkboxValue.length) {
        this.checkboxValue = []
      } else {
        this.checkboxValue = [""]
      }
    },
    changePayType(item) {
      this.selectedItem = item
      this.selected = item.value
    },
    validate() {
      const validations = [
        {
          condition: !this.form.price,
          message: "请输入付款金额",
        },
        {
          condition: !this.form.payeeId,
          message: "请输入收款人id号",
        },
        {
          condition: !this.form.remark,
          message: "请输入付款备注",
        },
        {
          condition: this.checkboxValue.length < 1,
          message: "请先同意资金担保协议",
        },
        {
          condition: !this.receiveInfo,
          message: "收款用户不存在",
        },
        {
          condition: this.form.payerId === this.form.payeeId,
          message: "收款用户不能和付款用户相同",
        },
      ]

      for (const { condition, message } of validations) {
        if (condition) {
          this.$toast(message)
          return false
        }
      }
      return true
    },
    submit() {
      if (this.receiveInfo) {
        if (this.userId == this.receiveInfo.id) {
          this.$toast('不能与自己进行担保交易')
          return
        }
      }
      if (this.validate()) {
        this.form.payerId = this.userId
        this.form.payerName = this.userName
        this.form.payeeName = this.receiveInfo.nickname
        if (this.selected === "1") {
          this.wechatPay()
        } else {
          this.balancePay()
        }
      }
    },
    wechatPay() {
      //创建订单
      let data = {
        ...this.form,
      }
      //后台计算单位是分
      data.price = Number(data.price) * 100
      api.user.guarantee_create(data).then((res) => {
        if (res.code === 200) {
          let query = {
            id: res.data.payOrderId,
            channelCode: "wx_lite",
            payerAvatar: this.userTx,
            memberUserAvatar: this.receiveInfo.avatar,
            ...data,
          }
          api.user.guarantee_pay(query).then((res) => {
            if (res.code === 200) {
              let payObj = JSON.parse(res.data.displayContent)
              uni.requestPayment({
                timeStamp: payObj.timeStamp,
                nonceStr: payObj.nonceStr,
                package: payObj.packageValue,
                signType: payObj.signType,
                paySign: payObj.paySign,
                success: (succ) => {
                  if (succ.errMsg === "requestPayment:ok") {
                    uni.hideLoading()
                    this.isDisable = false
                    this.$toast("支付成功～")
                    this.close()
                  }
                },
                fail: (err) => {
                  uni.hideLoading()
                  this.isDisable = false
                  this.$toast("支付失败！")
                },
              })
            }
          })
        }
      })
    },
    createOder() {
      //创建订单
      let data = {
        ...this.form,
      }
      //后台计算单位是分
      data.price = Number(data.price) * 100
      api.user.guarantee_create(data).then((res) => {
        if (res.code === 200) {
          let query = {
            id: res.data.payOrderId,
            channelCode: "wallet",
            payerAvatar: this.userTx,
            memberUserAvatar: this.receiveInfo.avatar,
            ...data,
          }
          api.user.guarantee_pay(query).then((res) => {
            if (res.code === 200) {
              this.$toast("支付成功～")
              this.close()
            }
          })
        }
      })
    },
    balancePay() {
      if (+this.balance < +this.form.price) {
        uni.showModal({
          title: "温馨提示",
          content: "账户余额不足，请先充值!",
          showCancel: true,
          cancelText: "取消",
          confirmText: "充值",
          success: (res) => {
            if (res.confirm) {
              uni.navigateTo({
                url: "/pages/wallet/recharge/index",
              })
              this.close()
            }
          },
        })
        return
      }
      uni.showModal({
        title: "温馨提示",
        content: "确认要使用余额支付？",
        showCancel: true,
        cancelText: "再想想",
        confirmText: "确认",
        success: (res) => {
          if (res.confirm) {
            this.createOder()
          }
        },
      })
    },
    // 关闭发送弹窗
    close() {
      this.$emit("close", false)
    },
    resetForm() {
      this.form = {
        payerId: "",
        payerName: "",
        price: "",
        payeeId: "",
        payeeName: "",
        remark: "",
      }
      this.selected = "1"
      this.receiveInfo = {}
      this.checkboxValue = []
    },
  },
  onLoad() {},
  onShow() {
  },
}
</script>

<style lang="scss" scoped>
@mixin content-flex($pitch) {
  display: flex;
  align-items: center;
  justify-content: $pitch;
}

.release_box {
  border-radius: 20rpx 20rpx 0px 0px;

  .head {
    padding: 30rpx;
    border-radius: 20rpx 20rpx 0px 0px;
    @include content-flex(flex-end);
  }

  .list {
    padding: 30rpx 0;
    border-bottom: 1px solid #e4e4e4;
    margin: 0 30rpx;

    &.flex_l {
      display: flex;
      align-items: center;

      input {
        flex: 1;
        font-size: 28rpx;
      }

      .title {
        width: 180rpx;
      }
    }

    .title {
      font-size: 28rpx;
      color: #3d3d3d;
      font-weight: 500;
      display: flex;
      align-items: center;

      span {
        font-size: 32rpx;
        color: #ff4441;
        margin-left: 6rpx;
      }
    }
  }

  .play_box {
    margin: 10rpx 30rpx 30rpx 30rpx;

    .title {
      font-size: 28rpx;
      color: #333;
      margin-bottom: 40rpx;
    }

    .radio-group-container {
      display: flex;
      flex-direction: column;
      margin-bottom: 30rpx;

      .radio-label {
        display: flex;
        align-items: center;
        justify-content: space-between;
        padding-bottom: 30rpx;
        /* 根据需要调整间距 */
        margin-bottom: 30rpx;
        border-bottom: 1px solid #e4e4e4;

        &:last-child {
          margin-bottom: 0;
        }
      }

      .text {
        font-size: 30rpx;
        color: #333;
        display: flex;
        align-items: center;

        img {
          width: 40rpx;
          height: 40rpx;
          margin-right: 10rpx;
        }

        span {
          color: #999;
          font-size: 24rpx;
        }
      }

      .gx {
        width: 40rpx;
        height: 40rpx;
      }
    }
  }

  .xieyi {
    width: 100%;
    text-align: center;
    font-size: 28rpx;
    color: #999999;
    display: flex;
    margin: 40rpx 30rpx 80rpx 30rpx;

    span {
      color: #23ac39;
    }

    p {
      margin-top: -4rpx;
    }
  }

  .btn {
    margin: 0 28rpx;
    text-align: center;
    padding-bottom: 50rpx;

    /deep/ .u-button {
      height: 96rpx;
      line-height: 96rpx;
      border-radius: 100rpx;
      background: #23ac39;
      font-size: 32rpx;
      text-align: center;
      font-weight: 500;
      color: #fff;
      border: none;
    }
  }
}

.user-info {
  display: flex;
  align-items: center;
  img {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    margin-right: 10rpx;
  }
}
</style>
